<?php
class ItemController extends Zend_Controller_Action
{
	private $_arrParam;
	private $_paniging = array('rowCount'=> 10, 'pageRange'=> 10);
	private $_userInfo;
	private $_config;
    private $_layout;
    public function init ()
    {
        $acl = new My_Acl();
        $auth = $acl->checkAllowed($this->_request);
        
        $this->_userInfo = $auth->getIdentity();
        $this->_arrParam['userId'] = $this->_userInfo['userId'];
       	$pageNumber = $this->_request->getParam('page',1);
    	$this->_paniging['page'] = $pageNumber;
    	$this->_arrParam['panigator'] = $this->_paniging;
		$this->_config = new Zend_Config_Ini(CONFIG_PATH . '/columns.ini',APPLICATION_ENV);
    }
    
    public function getcodeAction(){
	    Zend_Layout::getMvcInstance()->disableLayout();
	    $this->_helper->viewRenderer->setNoRender();
        $category           = (int)($this->_getParam('category'));
        $owner              = $this->_getParam('owner');
     
        $model_category           = new Default_Model_CategoryItem();
        $category_check = $model_category->getDataByID($category);
        
        if($category_check){
           
            $categoryCode = $category_check['categoryItemCode'];
            
            $owner_list = $this->_config->owner->toArray();
         
            foreach($owner_list as $key=>$row){
                if($row['name'] == $owner){
                    $ownerCode = $row['code'];
                    break;
                }
            }
            
            if(isset($categoryCode) && isset($ownerCode)){
                $model_item        = new Default_Model_Items();
                $code = "$categoryCode-$ownerCode-";
                if($category_check['categoryItemId'] == 15){
                    $code = $categoryCode;
                }
                $item_check = $model_item->checkMaxCode($code);
               
                if($item_check){
                    //echo $categoryCode,'-',$ownerCode;
                    if($category_check['categoryItemId'] == 15){
                        $stt =  (int)(substr($item_check['code'],3)) + 1;
                    }else{
                        $stt =  (int)(substr($item_check['code'],-3)) + 1;
                    }
                    $stt = '000'.$stt;
                    $stt =  substr($stt,-3);
                }else{
                    $stt = '001';
                }
                if($category_check['categoryItemId'] == 15){
                    echo $categoryCode,$stt;
                }else{
                    echo $categoryCode,'-',$ownerCode,'-',date("y"),$stt;
                }
            }
        }
    }
    
     public function freedomAction()
    {
        $this->getHelper('Layout')->disableLayout();
        $this->getHelper('ViewRenderer')->setNoRender();
        $itemsId=$this->_getParam('id');
        $equimentId=$this->_getParam('equi');
        if(!isset($equimentId) && !$equimentId)
        {
              $equimentId=0;
        }
        $modelItems=new Default_Model_Items();
        $modelItems->updateEquipmentidItem($itemsId,$equimentId);
    }
    public function listFreeAction()
    {
        $equimentId=0;
        $modelItems=new Default_Model_Items();
        $result=$modelItems->getItemspa($equimentId, $this->_paniging['page'], $this->_paniging['rowCount']);    
        if(count($result->toArray())<1)
        {
            $this->view->mess = "Không có thiết bị tự do nào!";
            $this->view->flag = "Null";
        }
        else
        { 
            $item_count = $modelItems->getCountItems($equimentId)->toArray();
            $this->view->itemList=$result->toArray();
           	$form = new Default_Form_Equipment();
    		$this->view->form = $form;
            $objPaginator= new My_Paginator();
            $totalItem = $item_count['Total'];
            $itemCountPerPage = $this->_paniging['rowCount'];
            $pageRange = $this->_paniging['pageRange'];
            $currentPage = $this->_paniging['page'];
            $panigator = $objPaginator->createPaginator($totalItem, $itemCountPerPage, $pageRange, $currentPage);
            $this->view->panigator = $panigator;
        }    
    }
    public function deleteAction()
    {
        $model_item = new Default_Model_Items();
        if($this->getRequest()->isPost()){
            $del = $this->getRequest()->getPost('del');
            if($del == 'Có'){
                $itemId = $this->getRequest()->getPost('itemId');
                $model_item->deleteItemByItemId($itemId);
                $session_check = new Zend_Session_Namespace('Check');
                $session_check->setExpirationSeconds(3);
                $session_check->status="Xóa thiết bị tự do thành công";
            }
            $this->_helper->redirector('list-free');
        }else{
            $id = $this->_getParam('id', 0);
            $this->view->item = $model_item->getDataByItemId($id);
            
        }
    }
    public function editAction()
    {
        $form = new Default_Form_Item();
    	$form->submit->setLabel( 'Lưu' );
    	$this->view->form = $form;
        //autocomplete
        $owner_list = $this->_config->owner->toArray();
        $temp = '';
        $stt = 1;
        foreach($owner_list as $row){
            if($stt != 1){
                $temp .= ', ';
            }
            $temp .= '"'.$row['name'].'"';
            ++$stt;
        }
        $this->view->owner_list = $temp;
        //danh nguoi ky hop dong de autocomplete
        $model_holder = new Default_Model_Holder();
        $model_item = new Default_Model_Items();
        $holder_list = $model_holder->getAllData();
        $temp = '';
        $stt = 1;
        foreach($holder_list as $row){
            if($stt != 1){
                $temp .= ', ';
            }
            $temp .= '"'.$row['holderName'].'"';
            ++$stt;
        }
        $this->view->holder_list = $temp;
        
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                //kiem tra ngay truoc va sau
                $startDate = $form->getValue('startDate');
                $duration = $form->getValue('duration');
                if($startDate > 0){
                        $startDate = date("Y-m-d",strtotime($startDate));
                    }else{
                        $startDate = 0;
                    }
                     if($duration > 0){
                        $duration = date("Y-m-d",strtotime($duration));
                    }else{
                        $duration = 0;
                    }			
                $mathDate = strtotime($duration) - strtotime($startDate);
            	if($mathDate < 0){
    	            $this->view->mess = "Ngày bắt đầu phải nhỏ hơn ngày kết thúc!";
                    $this->view->flag = "error";
		     	}//end if kiem tra ngay
				else{
				    $id = (int)($this->_getParam('id', 0));
                    $itemName = $form->getValue('itemName');
                    $serialNumber = $form->getValue('serialNumber');
                    $rentItem = $form->getValue('rentItem');
                    $rentEnd = $form->getValue('rentEnd');
                    $holders = $form->getValue('holders');
                    $priceNow = $form->getValue('priceNow');
                    $priceItem = $form->getValue('priceItem');
                    $history = $form->getValue('history');
                    $equipmentId=0;
                    $info = $form->getValue('info');
                    $addendums = $form->getValue('addendums');
                    $owner = $form->getValue('owner');
                    $expire = $form->getValue('expire');
                    
                	if($expire != ""){
						$expire = 1;
					}else{
						$expire = 0;
					}		
                    $createUser = $this->_userInfo['userId'];
                    $createDate = date('Y-m-d H:i:s');
                    $model_item->updateItem($id,$itemName, $serialNumber, $rentItem, $rentEnd, $priceItem, $equipmentId, $startDate, $duration,
                    $holders, $priceNow,$history, $info, $addendums, $owner, $expire, $createUser, $createDate);
                    $session_check = new Zend_Session_Namespace('Check');
                    $session_check->setExpirationSeconds(3);
                    $session_check->status="Sửa thiết bị tự do thành công";
    		      	$this->_helper->redirector('list-free','item');
                   
                }
    		}else{
    		    $this->view->mess = "vui lòng điền đầy đủ thông tin!";
                $this->view->flag = "error";
    			$form->populate($formData);
    		}
    	}else{
    		$id = (int)($this->_getParam('id', 0));
            $item = $model_item->getDataByItemId($id);
   			$form->populate($item);
    	}
    }
    
    public function addItemAction()
    {
        $form = new Default_Form_Item();
        $form->submit->setLabel('Thêm mới!');
        $this->view->form = $form;
        //danh sach tai san de autocomplete
        $owner_list = $this->_config->owner->toArray();
        $temp = '';
        $stt = 1;
        foreach($owner_list as $row){
            if($stt != 1){
                $temp .= ', ';
            }
            $temp .= '"'.$row['name'].'"';
            ++$stt;
        }
        $this->view->owner_list = $temp;
        //danh nguoi ky hop dong de autocomplete
        $model_holder = new Default_Model_Holder();
        $model_item = new Default_Model_Items();
        $holder_list = $model_holder->getAllData();
        $temp = '';
        $stt = 1;
        foreach($holder_list as $row){
            if($stt != 1){
                $temp .= ', ';
            }
            $temp .= '"'.$row['holderName'].'"';
            ++$stt;
        }
       
        $this->view->holder_list = $temp;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
                //kiem tra ngay truoc va sau
                $startDate = $form->getValue('startDate');
                $duration = $form->getValue('duration');
                if($startDate > 0){
                        $startDate = date("Y-m-d",strtotime($startDate));
                    }else{
                        $startDate = 0;
                    }
                     if($duration > 0){
                        $duration = date("Y-m-d",strtotime($duration));
                    }else{
                        $duration = 0;
                    }			
                $mathDate = strtotime($duration) - strtotime($startDate);
				if($mathDate < 0){
		            $this->view->mess = "Ngày bắt đầu phải nhỏ hơn ngày kết thúc!";
                    $this->view->flag = "error";
				}//end if kiem tra ngay
				else{
				    $code=$form->getValue('code');
                    $category=$form->getValue('category');                  
                    $itemName = $form->getValue('itemName');
                    $serialNumber = $form->getValue('serialNumber');
                    $rentItem = $form->getValue('rentItem');
                    $rentEnd = $form->getValue('rentEnd');
                    $holders = $form->getValue('holders');
                    $priceNow = $form->getValue('priceNow');
                    $priceItem = $form->getValue('priceItem');
                    $history = $form->getValue('history');
                    $equipmentId=0;
                    $info = $form->getValue('info');
                    $addendums = $form->getValue('addendums');
                    $owner = $form->getValue('owner');
                    $expire = $form->getValue('expire');
                    	
                    $createUser = $this->_userInfo['userId'];
                    $createDate = date('Y-m-d H:i:s');
                    $idadd=$model_item->addItem($itemName,$code, $category, $serialNumber, $rentItem, $rentEnd, $priceItem, $equipmentId, $startDate, $duration,
                    $holders, $priceNow,$history, $info, $addendums, $owner, $expire, $createUser, $createDate);
                    if(isset($idadd) && $idadd)
                    {
                        $session_check = new Zend_Session_Namespace('Check');
                        $session_check->setExpirationSeconds(3);
                        $session_check->status="Thêm item thành công";
                        $this->_redirect('/default/item/list-free');
                    }
                    else
                    {
                        $this->view->mess = "Thêm thất bại!";
                        $this->view->flag = "error";
                    }
                }//end else kiem tra ngay	
				
                }//end if
            else{//else isvalid
                $this->view->mess = "vui lòng điền đầy đủ thông tin!";
                $this->view->flag = "error";
                $form->populate($formData);
            }
        }
    }
}//end class






